'use strict'
/*
 * 解析XML文件
*/

const log = require('../log.js')

var xml2js = require('xml2js')
var Promise = require('bluebird')
var tpl = require('./tpl')

exports.parseXMLAsync = function(xml){
	return new Promise(function(resolve, reject){
		xml2js.parseString(xml, {trim: true}, function(err, content){
			if(err) reject(err)
				else resolve(content)
		})
	})
}

function formatMessage(result){
	var message = {}

	if(typeof result === 'object'){
		var keys = Object.keys(result)

		for (var i = 0; i <= keys.length; i++) {

			var item = result[keys[i]]
			var key = keys[i]

			if(!(item instanceof Array) || item.length === 0){	//判断item是不是数组和item的长度是不是0
				continue
			}
			if(item.length ===1){
				var val = item[0]

				if(typeof val === 'object'){	//在判断val是不是object类型
					message[key] = formatMessage(val)
				}
				else{
					message[key] = (val || '').trim()	//
					
				}
			}
			else{
				//如果item既不等于0也不等于1，说明有多个值
				message[key] = []

				for(var j = 0, k = item.length; j < k; j++) {
						message[key].push(formatMessage(item[j]))
				}
			}		

		}
	}
	return message
}
exports.formatMessage = formatMessage

//暴露一个tpl方法
exports.tpl = function(content, message){

	var info = {}
	var MsgType = 'text'
	var FromUserName = message.FromUserName
	var ToUserName = message.ToUserName

	if(Array.isArray(content)){
		MsgType = 'news'
	}

	info.MsgType = content.type || MsgType
	info.content = content
	info.createTime = new Date().getTime()
	info.ToUserName = FromUserName
	info.FromUserName = ToUserName
// log.info(content)
	return tpl.compiled(info)

}